package cn.wxxyhw.Dao;

import cn.wxxyhw.Entity.Liuyan;
import cn.wxxyhw.Util.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/**
 * 留言板
 * @Author: 洪稳
 * @Date: 2019/6/4
 */
@Repository
public class LiuyanDao {

    @Autowired
    private UserDao userDao;

    static QueryRunner queryRunner ;
    static {
        queryRunner = new QueryRunner(DataSourceUtil.getDataSource());
    }

    /**
     * 获取全部留言
     * @param name
     * @return
     */
    public List<Liuyan> getAllLiuyanByName(String name){
        List<Liuyan> lists = null;
        String sql ="select * from liuyan where toId = '"+name+"' order by id desc";
        try {
             lists = queryRunner.query(sql, new BeanListHandler<>(Liuyan.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return lists;
    }

    /**
     * 保存留言
     * @param liuyan
     */
    public void save(Liuyan liuyan) {
        String sql = "insert into liuyan(date,content,fromName,toName,fromImage,toId,fromId) values(?,?,?,?,?,?,?)";
        String fromImage = userDao.getImageByName(liuyan.getFromId());
        try {
            queryRunner.update(sql,liuyan.getDate(),
                                    liuyan.getContent(),
                                    liuyan.getFromName(),
                                    liuyan.getToName(),
                                    fromImage,
                                    liuyan.getToId(),
                                    liuyan.getFromId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除留言
     * @param parseInt
     */
    public void del(int parseInt) {
        String sql  = "delete  from liuyan where id = ?";
        try {
            int update = queryRunner.update(sql, parseInt);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
